package com.qyhl.webtv.module_live.teletext.newchatroom;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.live.TeleTextMessageBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.view.ViewPageFragment;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.qyhl.webtv.module_live.common.TeleTextInterface;
import com.qyhl.webtv.module_live.teletext.newchatroom.roomutil.ChatRoomConnectListener;
import com.qyhl.webtv.module_live.teletext.newchatroom.roomutil.NewChatRoomUtil;
import com.qyhl.webtv.module_live.utils.Event;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;

/**
 * 图文聊天室
 * Created by qyhl on 2017/7/6.
 */

public class NewTeleTextCommentFragment extends ViewPageFragment implements TeleTextInterface.TeleTextComment {
    @BindView(R2.id.comment_refresh)
    SmartRefreshLayout commentRefresh;
    @BindView(R2.id.chat_room)
    RecyclerView chatRoom;
    @BindView(R2.id.newmessage)
    ImageView newmessage;
    @BindView(R2.id.layout)
    LoadingLayout layout;

    private String chatRoomId;
    private NewChatRoomUtil newChatRoomUtil;
    private String type;
    private MultiItemTypeAdapter<TeleTextMessageBean> mAdapter;

    private List<TeleTextMessageBean> list;
    private ConcurrentLinkedQueue<TeleTextMessageBean> queue;

    public void setChatRoomId(String chatRoomId) {
        this.chatRoomId = chatRoomId;
    }

    public void setType(String type) {
        this.type = type;
    }

    public static NewTeleTextCommentFragment newInstance(String chatRoomId, String type) {
        NewTeleTextCommentFragment fragment = new NewTeleTextCommentFragment();
        fragment.setChatRoomId(chatRoomId);
        fragment.setType(type);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.live_newfragment_teletext_comment, container, false);
            ButterKnife.bind(this, rootView);
            BusFactory.getBus().register(this);
            init();//初始化
        }
        return rootView;
    }

    private void init() {
        layout.setStatus(LoadingLayout.Loading);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if ("0".equals(type)) {
                chatRoom.setNestedScrollingEnabled(true);
            } else {
                chatRoom.setNestedScrollingEnabled(false);
            }
        }
        chatRoom.setLayoutManager(new LinearLayoutManager(getContext()));
        list = new ArrayList<>();
        //配置刷新
        commentRefresh.setDisableContentWhenRefresh(true);
        commentRefresh.setEnableOverScrollBounce(true);
        commentRefresh.setEnableLoadMore(false);
        commentRefresh.setRefreshHeader(new MaterialHeader(getContext()));

        commentRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        commentRefresh.finishRefresh();
                    }
                }, 1500);

            }
        });

        //内容显示
        layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                layout.setStatus(LoadingLayout.Loading);
                if (newChatRoomUtil.isJoin()) {
                    //已经加入就重连
                    newChatRoomUtil.reconnect();
                } else {
                    configureChatRoom();
                }
            }
        });
        //新消息点击
        newmessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setNewMessage(View.GONE);
                chatRoom.scrollToPosition(mAdapter.getItemCount() - 1);
            }
        });
        //向上滚动监听
        chatRoom.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (RecyclerView.SCROLL_STATE_IDLE == newState) {
                    if (!chatRoom.canScrollVertically(1)) {
                        setNewMessage(View.GONE);
                    }
                }
            }
        });
        mAdapter = new MultiItemTypeAdapter<>(getContext(), list);
        mAdapter.addItemViewDelegate(new ChatRoomMyView(getContext()));
        mAdapter.addItemViewDelegate(new ChatRoomOtherView(getContext()));
        chatRoom.setAdapter(mAdapter);
        initChatRoom();
    }

    private void initChatRoom() {
        //初始化聊天室
        queue = new ConcurrentLinkedQueue<>();
        newChatRoomUtil = new NewChatRoomUtil();
        newChatRoomUtil.setConnectListener(new ChatRoomConnectListener() {
            @Override
            public void connect() {
                queue.clear();
                mHandler.sendEmptyMessage(2);
            }

            @Override
            public void message(TeleTextMessageBean textMessageBean) {
                queue.offer(textMessageBean);
                mHandler.sendEmptyMessage(0);
            }

            @Override
            public void connectFail() {
                mHandler.sendEmptyMessage(1);
            }
        });
        configureChatRoom();
    }

    private void configureChatRoom() {
        //配置聊天室
        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
            @Override
            public void login(boolean isLogin) {
                String nickName = CommonUtils.getInstance().getNickName();
                String headicon = CommonUtils.getInstance().getUserLogo();
                if (isLogin) {
                    String userName = CommonUtils.getInstance().getUserName();
                    newChatRoomUtil.setUserName(userName);
                    newChatRoomUtil.setNickName(nickName);
                    newChatRoomUtil.setLogo(headicon);
                    newChatRoomUtil.setRid(chatRoomId);
                } else {
                    newChatRoomUtil.setUserName("游客");
                    newChatRoomUtil.setNickName("游客");
                    newChatRoomUtil.setLogo("");
                    newChatRoomUtil.setRid(chatRoomId);
                }
                //加入聊天室
                newChatRoomUtil.join();
            }

            @Override
            public void error(String s) {
                Toasty.error(getActivity(), "网络错误").show();
            }
        });

    }

    @Override
    public void sendComment(String comment) {
        if (newChatRoomUtil != null) {
            if (newChatRoomUtil.send(comment)) {
                return;
            }
        }
        Toast.makeText(getActivity(), "发送失败，请稍后重试！", Toast.LENGTH_SHORT).show();

    }

    /**
     * eventBus 接收器
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void logined(Event.LoginMessage event) {
        if (event != null && event.isLogin()) {
            mHandler.removeCallbacksAndMessages(null);
            layout.setStatus(LoadingLayout.Loading);
            newChatRoomUtil.close();
            configureChatRoom();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        newChatRoomUtil.close();
        BusFactory.getBus().unregister(this);
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //umeng
        MobclickAgent.onPageStart("图文直播聊天室");
        MobclickAgent.onResume(getContext());
    }

    @Override
    public void onPause() {
        super.onPause();
        //umeng
        MobclickAgent.onPageEnd("图文直播聊天室");
        MobclickAgent.onPause(getContext());
    }

    private Handler mHandler = new MyHandler(this, Looper.getMainLooper());

    private static class MyHandler extends Handler {
        private final WeakReference<NewTeleTextCommentFragment> mActivity;

        public MyHandler(NewTeleTextCommentFragment activity, Looper mainLooper) {
            super(mainLooper);
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            NewTeleTextCommentFragment tel = mActivity.get();
            if (tel != null && tel.getActivity() != null && !tel.getActivity().isFinishing()) {
                switch (msg.what) {
                    case 0:
                        if (!tel.queue.isEmpty()) {
                            boolean isbotton = !tel.chatRoom.canScrollVertically(1);
                            while (!tel.queue.isEmpty()) {
                                TeleTextMessageBean bean = tel.queue.poll();
                                tel.list.add(bean);
                                String userName = CommonUtils.getInstance().getUserName();
                                if (bean.getUsername().equalsIgnoreCase(userName)) {
                                    //如果是自己的消息就滚到底部
                                    isbotton = true;
                                }
                                tel.mAdapter.notifyItemChanged(tel.mAdapter.getItemCount() - 1);
                            }
                            if (isbotton) {
                                tel.setNewMessage(View.GONE);
                                tel.chatRoom.scrollToPosition(tel.mAdapter.getItemCount() - 1);
                            } else {
                                tel.setNewMessage(View.VISIBLE);
                            }
                        }
                        break;
                    case 1:
                        tel.layout.setStatus(LoadingLayout.Error);
                        tel.layout.setErrorText("连接失败，点击重连！");
                        break;
                    case 2:
                        tel.list.clear();
                        tel.setNewMessage(View.GONE);
                        tel.mAdapter.notifyDataSetChanged();
                        tel.layout.setStatus(LoadingLayout.Success);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void setNewMessage(int visible) {
        if (newmessage.getVisibility() != visible) {
            newmessage.setVisibility(visible);
        }
    }
}